package nl.hva.three2learn.dao;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import nl.hva.three2learn.model.Event;

@Repository
public final class EventDaoImpl implements EventDao {

	@Autowired
	private SessionFactory sessionFactory;

	@Override
	public List<Event> findAllEvents(int limit) {
		
		if (limit < 1)
			throw new IllegalArgumentException("limit must be greater than 0");
		
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		
		Query q = session.createQuery("from Event e order by e.creationDate desc");
		q.setMaxResults(limit);
		
		List<Event> events = q.list();
		
		session.getTransaction().commit();
		
		return events;
	}

	@Override
	public List<Event> findAllEventsFrom(Date start) {
		return null;
	}
	
	@Override
	public void save(Event e) {
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		session.saveOrUpdate(e);
		session.getTransaction().commit();
	}
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
}
